<?php

class SiteController extends Controller {

    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'login', 'error', 'updatePhoto', 'exportUploadTxt', 'getDoneTxt','MovePhoto', 'fxl'),
                'users' => array('*'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('getPhoto', 'logout'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Declares class-based actions.
     */
    public function actions() {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex() {
        $this->render('index');
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest) {
                echo $error['message'];
            } else {
                $this->render('error', $error);
            }
        }
    }

    /**
     * Displays the contact page
     */
    public function actionContact() {
        $model = new ContactForm;
        if (isset($_POST['ContactForm'])) {
            $model->attributes = $_POST['ContactForm'];
            if ($model->validate()) {
                $headers = "From: {$model->email}\r\nReply-To: {$model->email}";
                mail(Yii::app()->params['adminEmail'], $model->subject, $model->body, $headers);
                Yii::app()->user->setFlash('contact', 'Thank you for contacting us. We will respond to you as soon as possible.');
                $this->refresh();
            }
        }
        $this->render('contact', array('model' => $model));
    }

    /**
     * Displays the login page
     */
    public function actionLogin() {
        $model = new LoginForm;

        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if (isset($_POST['LoginForm'])) {
            $model->attributes = $_POST['LoginForm'];
            // validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->login())
                $this->redirect(array('psi/index'));
        }
        // display the login form
        $this->render('login', array('model' => $model));
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

    //抓文件入库
    public function actionGetPhoto() {
        set_time_limit(0);
        if ($_POST['path']) {
            $path = Yii::app()->params['path'];
            $ftpPath = $_POST['path'];
            $myfile = Yii::app()->file->set($path, true);
            $rowset = $myfile->getContents();
            if ($rowset) {
                foreach ($rowset as $row) {
                    $file = Yii::app()->file->set($row, true);
                    $condition = new CDbCriteria();
                    $condition->addCondition("pname='" . $file->basename . "'");
                    $condition->addCondition("path='" . $ftpPath . "'");
                    $dfile = IteamPhoto::model()->find($condition);
                    unset($condition);
                    if (!$dfile) {
                        $msg .= Yii::app()->params['host'] . $ftpPath . $file->basename . '<br />';
                        $model = new IteamPhoto;
                        $model->pname = $file->basename;
                        $model->path = $ftpPath;
                        $model->psize = $file->size;
                        $model->pdate = date('Y-m-d H:i:s', $file->timeModified);
                        $model->save();
                        unset($model);
                    }
                }
            }
        }

        $this->render('photo', array('msg' => $msg));
    }

    //更新Photo表
    public function actionUpdatePhoto() {
        $condition = new CDbCriteria();
        $condition->addCondition('status=2');
        $condition->order = 'pname asc';
        $rowTable = IteamPhoto::model()->findAll($condition);
        unset($condition);
        if ($rowTable) {
            foreach ($rowTable as $row) {
                $productNo = explode('_', $row->pname);
                $productNo = $productNo[0];
                
                $product = Product::model()->find("ProductModel='".$productNo."'");
                if($product){
                    $condition = new CDbCriteria();
                    $condition->addCondition("ProductNo='" . $productNo . "'");
                    $productPhoto = Photo::model()->find($condition);
                    unset($condition);
                    if ($productPhoto) {
                        for ($i = 1; $i <= 13; $i++) {
                            if ($productPhoto['URL' . $i]) {
                                if ($productPhoto['URL' . $i] == Yii::app()->params['host'] . $row->path . $row->pname) {
                                    //如果重复了，就不要更新了
                                    $row->status = 11;
                                    $msg .= Yii::app()->params['host'] . $row->path . $row->pname . ' 已存在，不用更新<br />';
                                    break;
                                }
                            } else {
                                $productPhoto['URL' . $i] = Yii::app()->params['host'] . $row->path . $row->pname;
                                $productPhoto->save();
                                $row->status = 3;
                                $msg .= Yii::app()->params['host'] . $row->path . $row->pname . ' 更新成功，更新在了：' . 'URL' . $i . '<br />';
                                break;
                            }
                        }
                        if ($i == 14) {
                            $row->status = 12;
                            $msg .= Yii::app()->params['host'] . $row->path . $row->pname . ' 产品图没有空位<br />';
                        }
                    } else {
                        $model = new Photo();
                        $model->ProductNo = $product->ProductModel;
                        $model->ProductName = $product->ProductName;
                        $model->ProductDetail = $product->ProductDetail;
                        $model->URL1 = Yii::app()->params['host'] . $row->path . $row->pname;
                        $model->save();
                        $msg .= Yii::app()->params['host'] . $row->path . $row->pname . ' 更新成功，更新在了：' . 'URL1（新建记录）<br />';
                        $row->status = 3;
                    }
                    $row->save();
                    //移动文件，通过ftp上传,上没上传都得移动
                    $ftppath = $product->SubCategory . '\\' . $product->ProductModel;
                    $ftp = Yii::app()->ftp;
                    $ftp->chdir('/');
                    $ftp->mkdir($ftppath);
                    $ftp->chdir($ftppath);
                    $ftp->put($row->pname, Yii::app()->params['path'] . '\\' . $row->pname, FTP_BINARY);
                    unset($ftp);
                    //删除图片
                    $filename = Yii::app()->params['path'] . '\\' . $row->pname;
                    $file = Yii::app()->file->set($filename, true);
                    $file->delete();
                    
                }else{
                    $msg .= Yii::app()->params['host'] . $row->path . $row->pname . ' 没有找到相关产品<br />';
                }

                
            }
        }
        header("Content-Type:text/html;charset=utf-8");
        echo $msg;
    }

    //导出待上传文件
    public function actionExportUploadTxt() {
        $condition = new CDbCriteria();
        $condition->addCondition('status=0');
        $rowTable = IteamPhoto::model()->findAll($condition);
        unset($condition);
        if ($rowTable) {
            $photos = array();
            foreach ($rowTable as $row) {
                $photos[$row->pid] = $row->pid.'||'. $row->path . '||' .$row->pname;
            }
        }
        if ($photos) {
            $content = implode(',', $photos);
            $filename = Yii::app()->params['txtPath'] . '\\' . time() . '.txt';
            $myfile = Yii::app()->file->set($filename, true);
            if ($myfile->create() && $myfile->setContents($content)) {
                $condition = new CDbCriteria();
                $condition->addInCondition('pid', CHtml::listData($rowTable, 'pid', 'pid'));
                IteamPhoto::model()->updateAll(array('status' => 1), $condition);
                unset($condition);
                $msg = '导出成功';
            }
        } else {
            $msg = '无需要导出的内容';
        }
        header("Content-Type:text/html;charset=utf-8");
        echo '<script>alert("'.$msg.'");window.location.href="index.php"</script>';
        echo $msg;
    }
    
    //导入已上传完成的图片
    public function actionGetDoneTxt() {
        $path = Yii::app()->params['doneTxtPath'];
        $myfile = Yii::app()->file->set($path, true);
        $rowset = $myfile->getContents();
        if ($rowset) {
            foreach ($rowset as $row) {
                $file = Yii::app()->file->set($row, true);
                $content = $file->getContents();
                if ($content) {
                    $idArr = explode(',', $content);
//                    var_dump($idArr);exit;
                    $condition = new CDbCriteria();
                    $condition->addInCondition('pid', $idArr);
                    $condition->addCondition('status=1');
                    IteamPhoto::model()->updateAll(array('status' => 2), $condition);
                    unset($condition);                    
                }
                $file->delete();
            }
        }
    }
    
    public function actionMovePhoto() {
        $path = Yii::app()->params['path'];
        $myfile = Yii::app()->file->set($path, true);
        $rowset = $myfile->getContents();
        if ($rowset) {
            foreach ($rowset as $row) {
                $file = Yii::app()->file->set($row, true);
                if ($file->isFile) {
                    $productNo = explode('_', $file->basename);
                    $productNo = $productNo[0];
                    $product = Product::model()->find("ProductModel='".$productNo."'");
                    if($product){
                        $ftppath = $product->SubCategory . '\\' . $product->ProductModel;
                        echo $ftppath;
                        $ftp = Yii::app()->ftp;
                        $ftp->chdir('/');
                        var_dump($ftp->mkdir($ftppath));
                        $ftp->chdir($ftppath);
                        $ftp->put($file->basename, $path . '\\' . $file->basename, FTP_BINARY);
                        unset($ftp);
                        //删除图片
                        $file->delete();
                        echo '<br />';
                    }
                }
            }
        }
    }

    //test
    public function actionFxl() {
        $path = 'F:\111';
        $myfile = Yii::app()->file->set($path, true);
        $rowset = $myfile->getContents();
        if ($rowset) {
            foreach ($rowset as $row) {
                $file = Yii::app()->file->set($row, true);
                if ($file->isFile) {
                    $productNo = explode('_', $file->basename);
                    $productNo = $productNo[0];
                    $product = Product::model()->find("ProductModel='".$productNo."'");
                    if($product){
                        $ftppath = $product->SubCategory . '\\' . $product->ProductModel;
                        echo $ftppath;
                        $ftp = Yii::app()->ftp;
                        $ftp->chdir('/');
                        var_dump($ftp->mkdir($ftppath));
                        $ftp->chdir($ftppath);
                        $ftp->put($file->basename, $path . '\\' . $file->basename, FTP_BINARY);
                        unset($ftp);
                        //删除图片
//                        $file->delete();
                        echo '<br />';
                    }
                }
            }
        }
    }

}